package com.umer.pinban.user;

import android.app.Dialog;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.common.CommonApplication;
import com.common.base.activity.BaseActivity;
import com.common.bean.InfoResult;
import com.common.bean.UserInfo;
import com.common.db.UserDao;
import com.common.okhttp.OkEntityRequest;
import com.common.ui.barlibrary.ImmersionBar;
import com.common.ui.edittext.CleanableEditText;
import com.common.utils.Constants;
import com.common.utils.MD5Utils;
import com.common.utils.SpUtil;
import com.common.utils.screen.ScreenUtil;
import com.umer.pinban.AppHolder;
import com.umer.pinban.HomeActivity;
import com.umer.pinban.R;

public class LoginActivity extends BaseActivity {

    CleanableEditText etPhone;
    CleanableEditText etPassword;
    Button btnLogin;
    TextView tvForgetPassword;
    LinearLayout llRegister;
    //1欢迎界面过来的 2退出登录 3登录过期
    private int flag;
    private UserDao userDao;
    private String password, account;
    private UserInfo userInfo;
    private long firstTime = 0;

    @Override
    public boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                //是否可以修改导航栏颜色，默认为true
                .navigationBarEnable(true)
                //导航栏颜色，不写默认黑色
                .navigationBarColor(com.common.R.color.barcolor)
                .statusBarColor(com.common.R.color.white)
                //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .init();
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return null;
    }

    @Override
    public boolean isSupportSwipeBackEnabled() {
        return false;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    public void init() {
        etPhone = (CleanableEditText) findViewById(R.id.et_phone);
        etPassword = (CleanableEditText) findViewById(R.id.et_password);
        btnLogin = (Button) findViewById(R.id.btn_login);
        tvForgetPassword = (TextView) findViewById(R.id.tv_forget_password);
        llRegister = (LinearLayout) findViewById(R.id.ll_register);

        flag = getIntent().getIntExtra("flag", 0);
        userDao = new UserDao(this);
        userInfo = userDao.query();
        if (userInfo != null) {
            etPhone.setText(userInfo.getPhone());
            etPassword.setText(userInfo.getPassword());
        }
        boolean flag = SpUtil.getBoolean(LoginActivity.this, "agree", false);
        if (!flag) {
            createDialogOne();
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                account = etPhone.getText().toString().trim();
                password = etPassword.getText().toString().trim();
                //验证用户名和密码
                if (validateAccount(account) && validatePassword(password)) {
                    showProgress("正在登录...");
                    OkEntityRequest<UserInfo> request = new OkEntityRequest<>(com.common.R.id.login,
                            Constants.USER_LOGIN, UserInfo.class);
                    request.addParams("phone", account);
                    request.addParams("password", getMD5(password));
                    requestOkhttpEntity(request);
                }
            }
        });
        tvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchTo(LoginActivity.this,ForgetPasswordActivity.class,false);
            }
        });
        llRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchTo(LoginActivity.this,RegisterActivity.class,false);
            }
        });
    }

    @Override
    public void loadData() {

    }

    @Override
    protected void onSuccess(int what, InfoResult t) {
        hideProgress();
        if(what ==R.id.login) {
            hideProgress();
            UserInfo userInfo = (UserInfo) t.getT();
            userInfo.setPhone(etPhone.getText().toString().trim());
            userInfo.setPassword(etPassword.getText().toString().trim());
            CommonApplication.getInstance().setUserInfo(userInfo);
            userDao.deleteAll();
            userDao.add(userInfo);
            switchTo(this, HomeActivity.class, true);
        }
    }

    @Override
    protected void onFail(int what, InfoResult t) {
        hideProgress();
        if (what == R.id.login) {
            hideProgress();
            showToast(t.getDesc());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(flag == 3){
                if (secondTime - firstTime < 2000) {
                    AppHolder.getInstance().finishAllActivitys();
                    AppHolder.getInstance().exitClient();
                } else {
                    Toast.makeText(getApplicationContext(), "再按一次返回键退出", Toast.LENGTH_SHORT).show();
                    firstTime = System.currentTimeMillis();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 验证用户名
     *
     * @param account
     * @return
     */
    private boolean validateAccount(String account) {
        if (TextUtils.isEmpty(account)) {
            showToast("请输入手机号码");
            return false;
        }
        return true;
    }

    /**
     * 验证密码
     *
     * @param password
     * @return
     */
    private boolean validatePassword(String password) {
        if (TextUtils.isEmpty(password)) {
            showToast("请输入密码");
            return false;
        }
        if (password.length() < 6 || password.length() > 18) {
            showToast("密码长度为6-18位");
            return false;
        }
        return true;
    }

    private String getMD5(String val) {
        return getString(MD5Utils.getInstance().toMD5(val));
    }

    private String getString(String val) {
        if (!TextUtils.isEmpty(val)) {
            String firstPart = val.substring(0, 2);
            String twoPart = val.substring(2, val.length());
            return twoPart + firstPart;
        }
        return "";
    }

    //=========================================================================================
    private Dialog dialogOne;
    private TextView tv1, tv2;

    private Dialog createDialogOne() {
        if (dialogOne == null) {
            dialogOne = new Dialog(this, com.common.R.style.ActionSheetDialogStyle);
            //填充对话框的布局
            View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_user_xieyi, null);
            tv1 = (TextView) inflate.findViewById(R.id.tv1);
            tv2 = (TextView) inflate.findViewById(R.id.tv2);
            tv1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonApplication.getInstance().exitClient();
                }
            });
            tv2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialogOne.isShowing()) {
                        SpUtil.putBoolean(LoginActivity.this, "agree", true);
                        dialogOne.dismiss();
                    }
                }
            });
            //将布局设置给Dialog
            dialogOne.setContentView(inflate);
            //设置点击屏幕不消失
            dialogOne.setCanceledOnTouchOutside(false);
            //设置点击返回键不消失
            dialogOne.setCancelable(false);
            Window dialogWindow = dialogOne.getWindow();
            WindowManager.LayoutParams windowparams = dialogWindow.getAttributes();
            //设置Dialog从窗体底部弹出
            dialogWindow.setGravity(Gravity.CENTER);
            Rect rect = new Rect();
            View view1 = dialogWindow.getDecorView();
            view1.getWindowVisibleDisplayFrame(rect);
            windowparams.width = ScreenUtil.getInstance().getScreenWidth();
            dialogWindow.setAttributes(
                    (WindowManager.LayoutParams) windowparams);
            //获得窗体的属性
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            lp.y = 10;//设置Dialog距离底部的距离
//            //将属性设置给窗体
//            dialogWindow.setAttributes(lp);
            dialogOne.show();
        }
        return dialogOne;
    }
}
